//
//  TSMainDetailViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/15.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

class TSMainDetailViewController: TSBaseViewController {
    
    var model : TSMainPageModel!
    
    lazy var dataSource : [TSRecordModel] = []
    
    var tableController : TSBaseTableViewController!
    
    lazy var footerView : TSProfitFooterView = {
        var footer = TSProfitFooterView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 305))
        footer.delegate = self
        return footer
    }()
    
    lazy var recordAlert : TSDetailRecordAlertView = {
        var record = TSDetailRecordAlertView.init(frame: UIScreen.main.bounds)
        record.delegate = self
        record.isHidden = true
        return record
    }()
    
    lazy var detailAlert : TSRecordAlertView = {
        var detail = TSRecordAlertView.init(frame: UIScreen.main.bounds)
        detail.isHidden = true
        return detail
    }()
    
    func updateVc(model:TSMainPageModel?) {
        
        guard model != nil else {
            return
        }
        
        TSLog("倒计时结束，详情页刷新")
        self.model = model
        tableController.tableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationTitle(title: model.title)
        configViews()
        
        requestRecordDatas(type: model.title == "幸运飞艇" ? "1" : "2")
    }
}

//MARK: - TSProfitFooterViewDelegate
extension TSMainDetailViewController : TSProfitFooterViewDelegate {
    
    func didClickRecord() {
        recordAlert.isHidden = false
    }
    
    func completeInvest(_ args: (Array<String>, String)) {
        getInvest(args)
    }
}

//MARK: - TSDetailRecordAlertViewDelegate
extension TSMainDetailViewController : TSDetailRecordAlertViewDelegate {
    
    func tradeWillBeRevoke(id: String) {
        revokeOrder(id: id)
    }
    
    func scanRecordDetail(model: TSRecordModel) {
        detailAlert.setupView(model: model)
        detailAlert.isHidden = false
    }

}

//MARK: - UITableViewDelegate
extension TSMainDetailViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 10))
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        if section == 1 {
            return self.footerView
        }
        
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        section == 1 ? 305 : 0.001
    }
}

//MARK: - UITableViewDataSource
extension TSMainDetailViewController : UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell : UITableViewCell?
        
        if indexPath.section == 0 {
            
            var profitCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSProfitTableViewCell.self)) as? TSProfitTableViewCell
            
            if profitCell == nil {
                profitCell = TSProfitTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSProfitTableViewCell.self))
            }
            
            profitCell?.refreshCell()
            
            cell = profitCell
            
        } else {
            
            var resultCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSProfitResultTableViewCell.self)) as? TSProfitResultTableViewCell
            
            if resultCell == nil {
                resultCell = TSProfitResultTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSProfitResultTableViewCell.self))
            }
            
            resultCell?.setupCell(model: model)
            
            cell = resultCell
        }
        
        return cell!
    }
    
}

//MARK: - Network Request
extension TSMainDetailViewController {
    
    func requestRecordDatas(type:String) {

        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getInvsetRecord(type: type), showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            
            self.dataSource.removeAll()
            
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSRecordModel.deserialize(from: item)
                    if let model = tempModel {
                        self.dataSource.append(model)
                    }
                }
            }
            self.recordAlert.dataSource = self.dataSource
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 撤单 */
    func revokeOrder(id:String) {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.revokeOrder(id: id), showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                CBToast.showToastAction(message: "撤单成功")
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                self.requestRecordDatas(type: self.model.title == "幸运飞艇" ? "1" : "2")
            }
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 下注 */
    func getInvest(_ args: (Array<String>, String)) {

        let array = args.0
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getInvest(qihao: "\(model.current)", jizhu: args.1, qufen: model.title == "幸运飞艇" ? "1" : "2", one: array[0], two: array[1], three: array[2], four: array[3]), showHUD: true, success: { (data) in

            CBToast.hiddenToastAction()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                CBToast.showToastAction(message: "投注成功")
            }
            self.requestRecordDatas(type: self.model.title == "幸运飞艇" ? "1" : "2")
            self.requestUserInfo()

        }) { (error) in
            
            CBToast.hiddenToastAction()
            
        }
    }
    
    /** 刷新用户信息 */
    func requestUserInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: true, success: { (data) in
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.tableController.tableView.reloadData()
            
        }) { (error) in
            
        }
    }
}


//MARK: - Initialize
extension TSMainDetailViewController {
    
    func configViews() {
        
        tableController = TSBaseTableViewController.init(style: .grouped)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        tableController.tableView.estimatedRowHeight = 100
        tableController.tableView.rowHeight = UITableView.automaticDimension
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        UIApplication.shared.keyWindow!.addSubview(recordAlert)
        UIApplication.shared.keyWindow!.addSubview(detailAlert)
    }
}
